﻿using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using CustomerModel = ERP.Team.ProductionSystem.CustomerModel;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 客户服务实现类
    /// </summary>
    public class CustomerServices : ApplicationService, ICustomerServices
    {
        private readonly IRepository<CustomerModel, int> _customerRepository;

        public CustomerServices(IRepository<CustomerModel, int> customerRepository)
        {
            _customerRepository = customerRepository;
        }

        public async Task<CustomerDto> GetAsync(int id)
        {
            var customer = await _customerRepository.GetAsync(id);
            return ObjectMapper.Map<CustomerModel, CustomerDto>(customer);
        }

        public async Task<PagedResultDto<CustomerDto>> GetListAsync(GetCustomerInputDto input)
        {
            // layui框架在请求分页数据时，传递的是页码（page number），而非要跳过的记录数（skip count）。
            // ABP框架的 .PageBy() 方法需要的是 skip count。
            // 因此，我们需要在这里进行转换：(页码 - 1) * 每页数量
            input.SkipCount = (input.SkipCount > 0 ? input.SkipCount - 1 : 0) * input.MaxResultCount;
            
            var queryable = await _customerRepository.GetQueryableAsync();

            var query = queryable
                .WhereIf(!string.IsNullOrWhiteSpace(input.CustomerCode), x => x.CustomerCode.Contains(input.CustomerCode))
                .WhereIf(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIf(!string.IsNullOrWhiteSpace(input.CustomerNiciname), x => x.CustomerNiciname.Contains(input.CustomerNiciname))
                .WhereIf(input.CustomerIsTrue.HasValue, x => x.CustomerIsTrue == input.CustomerIsTrue);
            
            if (string.IsNullOrWhiteSpace(input.Sorting))
            {
                input.Sorting = "Id desc";
            }
            else if (!input.Sorting.Contains("Id", StringComparison.OrdinalIgnoreCase))
            {
                input.Sorting += ", Id desc";
            }

            var totalCount = await AsyncExecuter.CountAsync(query);

            var items = await AsyncExecuter.ToListAsync(
                query.OrderBy(input.Sorting)
                     .PageBy(input)
            );

            var dtoList = ObjectMapper.Map<List<CustomerModel>, List<CustomerDto>>(items);
            return new PagedResultDto<CustomerDto>(totalCount, dtoList);
        }

        public async Task<CustomerDto> CreateAsync(CreateUpdateCustomerDto input)
        {
            var customer = ObjectMapper.Map<CreateUpdateCustomerDto, CustomerModel>(input);
            var result = await _customerRepository.InsertAsync(customer);
            return ObjectMapper.Map<CustomerModel, CustomerDto>(result);
        }

        public async Task<CustomerDto> UpdateAsync(int id, CreateUpdateCustomerDto input)
        {
            var customer = await _customerRepository.GetAsync(id);
            ObjectMapper.Map(input, customer);
            var result = await _customerRepository.UpdateAsync(customer);
            return ObjectMapper.Map<CustomerModel, CustomerDto>(result);
        }

        public async Task DeleteAsync(int id)
        {
            await _customerRepository.DeleteAsync(id);
        }

        public async Task DeleteManyAsync(IEnumerable<int> ids)
        {
            await _customerRepository.DeleteManyAsync(ids);
        }
    }
}
